import React from 'react';
import { Form, Button, Drawer, message, Modal } from 'antd';
import {
    createAndUpdateTalk,
    cancelDimissionTalk,
    getDimissionTalkDetail
} from '@/pages/OnboardAndLeave/LeaveManagement/service';
import { useRequest, defaultFormatResult } from '@/hooks';
import { momentToString, renderHiddenField, getUser } from '@/utils/utils';
import LimitInput from '@/components/LimitInput';

import ApplyForm from './ApplyForm';
import { formatList, getApplyData } from './index';

const formItemLayout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 14
    }
};

const ConfirmModal = Form.create()(({ form, modalVisible, setModalVisible, handleCancel }) => (
    <Modal
        title="撤销面谈"
        visible={modalVisible}
        width={680}
        onOk={() => {
            form.validateFields(async (err, values) => {
                if (!err) {
                    handleCancel(values);
                }
            });
        }}
        onCancel={() => {
            setModalVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        zIndex={2000}
    >
        <Form.Item required label="理由" {...formItemLayout}>
            {form.getFieldDecorator('reason', {
                rules: [
                    { required: true, message: '请输入理由' },
                    {
                        min: 1,
                        max: 4000,
                        message: '请输入1~4000个字符'
                    }
                ]
            })(<LimitInput area rows={4} placeholder="请输入" maxLength={4000} />)}
        </Form.Item>
    </Modal>
));

const updateTime = (date, time) => date.hour(time.hour()).minute(time.minute());

const TalkDrawer = ({
    visible,
    setVisible,
    form,
    initialData,
    employeeName,
    employeeCode,
    processInstanceId,
    callback
}) => {
    const [modalVisible, setModalVisible] = React.useState(false);

    const { run, loading: createLoading } = useRequest(param => createAndUpdateTalk(param), {
        manual: true,
        ...defaultFormatResult
    });

    const { run: runCancel } = useRequest((param = {}) => cancelDimissionTalk({ processInstanceId, ...param }), {
        manual: true,
        ...defaultFormatResult
    });

    const { data: originData = [], run: refresh } = useRequest(() => getDimissionTalkDetail(processInstanceId), {
        ready: !!processInstanceId && !initialData,
        ...defaultFormatResult
    });

    let applyData = initialData ?? {};

    if (!initialData) {
        const list = formatList(originData);
        applyData = getApplyData(list);
    }

    const showCancelButton = !!applyData.id; // 非编辑也可

    const submitCallback = callback || refresh; // 不太好的设计

    const isNew = !applyData.id;

    // 如果是新增，把自己先加入到面试参与人，WTF
    if (isNew) {
        const user = getUser();
        applyData.interviewEmployeeCodeList = [user.employeeCode];
    }

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const { schedule, ...rest } = values;
                const result = await run({
                    ...rest,
                    processInstanceId,
                    employeeCode,
                    employeeName,
                    interviewSourceName: `${employeeName}的面谈`,
                    interviewDate: momentToString(values.interviewDate),
                    interviewStartTime: momentToString(updateTime(values.interviewDate, values.interviewStartTime)),
                    interviewEndTime: momentToString(updateTime(values.interviewDate, values.interviewEndTime))
                });
                if (result) {
                    message.success('提交成功');
                    setVisible(false);
                    submitCallback();
                }
            }
        });
    };

    const handleCancel = async param => {
        const result = await runCancel(param);
        if (result) {
            message.success('撤销面谈成功');
            setVisible(false);
            setModalVisible(false);
            submitCallback();
        }
    };

    return (
        <Drawer
            title={`${isNew ? '发起' : '修改'}面谈`}
            placement="right"
            onClose={() => {
                setVisible(false);
            }}
            visible={visible}
            getContainer={document.body}
            style={{ position: 'absolute' }}
            width="70%"
        >
            <div style={{ paddingBottom: 16 }}>
                <ApplyForm form={form} employeeName={employeeName} data={applyData} />
            </div>
            {renderHiddenField({
                field: 'id',
                initialValue: applyData.id,
                form
            })}
            <div
                style={{
                    position: 'absolute',
                    right: 0,
                    bottom: 0,
                    width: '100%',
                    padding: '10px 16px',
                    background: '#fff',
                    display: 'flex',
                    justifyContent: 'center'
                }}
            >
                <Button loading={createLoading} onClick={handleSubmit} type="primary" style={{ marginRight: 20 }}>
                    确定
                </Button>
                <Button
                    onClick={() => {
                        setVisible(false);
                    }}
                >
                    取消
                </Button>
                {showCancelButton && (
                    <>
                        <Button
                            type="danger"
                            ghost
                            style={{ marginLeft: 20 }}
                            onClick={() => {
                                setModalVisible(true);
                            }}
                        >
                            撤销面谈
                        </Button>
                        <ConfirmModal {...{ handleCancel, modalVisible, setModalVisible }} />
                    </>
                )}
            </div>
        </Drawer>
    );
};

export default Form.create()(TalkDrawer);
